<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="roleFilterSelectValue" placeholder="角色" filterable clearable multiple collapse-tags class="filter-item" style="width: 200px"
        @change = "handleRoleFilterSelect">
        <el-option v-for="(item,index) in roleListData" :key="index" :label="item.name+'('+item.id+')'" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.enabled" placeholder="是否启用" clearable class="filter-item" style="width: 130px">
        <el-option :key="true" :label="'是'" :value="true" />
        <el-option :key="false" :label="'否'" :value="false" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-if="buttons.create" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-if="buttons.export" v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="userName" align="left">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="left">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" prop="avatar" align="left">
        <template slot-scope="{row}">
          <el-image style ="width:100px; height: 100px" :src="row.avatar"/>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email" align="left">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" prop="phoneNumber" align="left">
        <template slot-scope="{row}">
          <span>{{ row.phoneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="roles" align="left">
        <template slot-scope="{row}">
          <el-tag style="margin-right: 5px; margin-bottom: 5px;" v-for="(item,index) in row.roles" :key="index">
            {{ item | roleFilter }}
          </el-tag>
        </template>
      </el-table-column> 
      <el-table-column label="是否启用" prop="enabled" sortable="custom" align="center" width="120px" :class-name="getSortClass('enabled')">
        <template slot-scope="{row}">
          <el-tag :type="row.enabled ? 'success' : 'danger'">
            {{ row.enabled ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="buttons.update"  type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="buttons.delete"  size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="200px" style="width: 80%;margin-left:50px;">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item v-if="dialogStatus==='create'" label="密码" prop="password">
          <el-input v-model="temp.password" type='password' />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="temp.avatar" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="temp.phoneNumber" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-checkbox-group v-model="temp.roles">
            <el-checkbox v-for="(item,index) in roleListData" :key="index" :label="item.name" :value="item.name">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-switch v-model="temp.enabled" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Create, Update, Delete, Get, GetPagedList } from '@/api/user'
import { GetUserMenuList } from '@/api/auth'
import { GetList as GetRoleList } from '@/api/role'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

let that
export default {
  name: 'User',
  components: { Pagination},
  directives: { waves },
  filters: {
    roleFilter(name) {
      return that.roleListData.find(item => item.name == name)?.name
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,  
      buttons:{
        create:false,
        update:false,
        delete:false,
        detail:false,
        export:true
      },
      roleListData: [],
      roleFilterSelectValue:null,
      downloadLoading: false,
      pvData: [],
      dialogPvVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        userName: [{ required: true, message: '用户名必填', trigger: 'change' }],
        password: [{ required: true, message: '密码必填', trigger: 'change' }],
        roles: [{ required: true, message: '角色必选', trigger: 'change' }],
        enabled: [{ required: true, message: '是否启用必选', trigger: 'change' }]
      },
      temp: {
        id: undefined,
        userName: null,
        password: null,
        name: null,
        avatar: null,
        email: null,
        phoneNumber: null,
        roles: [],
        enabled: true
      },
      listQuery: {
        pageIndex: 1,
        pageSize: 10,
        sorting: null,
        name: null,
        roles: null,
        enabled: null
      },
      pagedList: {
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        items: null
      }
    }
  },
  beforeCreate () {
	  that = this
  },
  created() {
    this.getButtonPermissions()
    this.loadRoleData()
    this.getList()
  },
  methods: {
    getButtonPermissions(){
      GetUserMenuList().then(response => {
        if(response.data){
          let menus = response.data.filter(item=>item.parentId==this.$route.meta.parentId && item.type==2)
          this.buttons = {
            create:menus.some(item=>item.permission.includes(".Create")),
            update:menus.some(item=>item.permission.includes(".Update")),
            delete:menus.some(item=>item.permission.includes(".Delete")),
            detail:menus.some(item=>item.permission.includes(".Detail")),
            export:menus.some(item=>item.permission.includes(".Export"))
          }
        }
      })
    },
    loadRoleData() {
      GetRoleList().then((response)=>{
        response.data.forEach(item=>{
          this.roleListData.push(item)
        })
      })
    },
    getList() {
      this.listLoading = true
      GetPagedList(this.listQuery).then(response => {
        this.pagedList = response.data;
        this.list = this.pagedList.items
        this.total = this.pagedList.totalCount
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      })
    },
    handleFilter() {
      this.listQuery.pageIndex = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: null,
        password: null,
        name: null,
        avatar: null,
        email: null,
        phoneNumber: null,
        roles: [],
        enabled: true
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if(this.temp.roles){
            this.temp.roles = this.temp.roles.join(',')
          }
          Create(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
          })
        }
      })
    },
    handleUpdate(row) {
      this.listLoading = true
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      Get({id:row.id}).then(response => {
        let data = response.data
        this.temp.id = data.id
        this.temp.userName = data.userName
        this.temp.name = data.name
        this.temp.avatar = data.avatar
        this.temp.email = data.email
        this.temp.phoneNumber = data.phoneNumber
        this.temp.roles = data.roles.map(item => item)
        this.temp.enabled = data.enabled
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let tempData = {
            id: undefined,
            name: null,
            avatar: null,
            email: null,
            phoneNumber: null,
            roles: null,
            enabled: true
          }
          this.tempData = {
            id: this.temp.id,
            name: this.temp.name,
            avatar: this.temp.avatar,
            email: this.temp.email,
            phoneNumber: this.temp.phoneNumber,
            enabled: this.temp.enabled
          }
          console.log('1', this.tempData)
          if(this.temp.roles){
            this.tempData.roles = this.temp.roles.join(',')
          }
          console.log('2', this.tempData)
          Update(this.tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.listLoading = true
      Delete({id:row.id}).then(response => {
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.handleFilter()
      })
    },
    sortChange(data) {
      const { prop, order } = data 
      if(prop && order){
        this.listQuery.sorting = prop + (order === 'ascending' ? ' ascending' : ' descending')
      }
      else {
        this.listQuery.sorting = null
      }
      this.handleFilter()
    },
    getSortClass: function(key) {
      if(this.listQuery.sorting){
        const items = this.listQuery.sorting.split(' ')
        if(items[0] == key){
          return items[1]
        }
      }
      return null
    },
    handleRoleFilterSelect(node){
      this.listQuery.roles = null
      if(node){
        this.listQuery.roles = node.join(',')
      }
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID','用户名','名称','邮箱','手机号码', '角色', '是否启用']
        const filterVal = ['id', 'userName', 'name','email','phoneNumber', 'roles', 'enabled']
        const data = this.list.map(v => filterVal.map(j => {
          if (j === 'roles') {
            let roleNames = v[j].join(',')
            // v[j].forEach(role=>{
            //   let name = this.roleListData.find(item => item.id == roleId)?.name
            //   if(name){
            //     roleNames.push(name)
            //   }
            // })
            return roleNames.join(',')
          }
          else if (j === 'enabled') {
            return v[j] === true ? '是' : '否'
          }
          else {
            return v[j]
          }
        }))
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'user-list'
        })
        this.downloadLoading = false
      })
    }
  }
}
</script>
